﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using ZX.Common.Extend;
using ZX.BLL.Extend;
using System.Threading.Tasks;
using System.Data;
using ZX.EHR.Library;
using System.Text;
using ZX.Web.UI.Controls;
namespace ZX.WebApp.Crm.Hodometer
{
    public partial class Calendar : ListPage
    {
        private string sb
        {
            get 
            {
                if (ViewState["sb"] == null)
                    return "";
                else
                    return ViewState["sb"].ToString();
            }
            set 
            {
                ViewState["sb"] = value;
            }
        }
        System.Globalization.Calendar calender = System.Globalization.CultureInfo.InvariantCulture.Calendar;
        private int year //定义年的变量的初始值
        {
            get
            {
                if (ViewState [ "Year" ]!=null )
                
                {
                    if ( int.Parse ( ViewState [ "Year" ].ToString ( ) ) > 9999 && int.Parse ( ViewState [ "Year" ].ToString ( ) ) < 1000 )
                    {
                        return DateTime.Now.Year;
                    }
                    else
                    {
                        return int.Parse ( ViewState [ "Year" ].ToString ( ) );
                    }
                
                }
                else
                {
                    return DateTime.Now.Year;
                }
            }
            set
            {
                ViewState [ "Year" ] = value;
            }
        }
        private int month       //定义月的变量的初始值
        {
            get
            {
                if ( ViewState [ "Month" ]!=null )
                 {
                     if ( int.Parse ( ViewState [ "Month" ].ToString ( ) ) < 0 && int.Parse ( ViewState [ "Month" ].ToString ( ) ) >= 13 )
                     {
                            return DateTime.Now.Month;
                     }
                     else
                     {
                         return int.Parse ( ViewState [ "Month" ].ToString ( ) );
                     }
                }
                else
                {
                    return DateTime.Now.Month;
                }
            }
            set
            {
                ViewState [ "Month" ] = value;
            }
        }
        private int day           //定义日的变量的初始值
       {
           get
           {
               if ( ViewState [ "Day" ] != null )
               {
                   if ( int.Parse ( ViewState [ "Day" ].ToString ( ) ) < 0 && int.Parse ( ViewState [ "Day" ].ToString ( ) ) > 31 )
                   {
                       return DateTime.Now.Day;
                   }
                   else
                   {
                       return int.Parse ( ViewState [ "Day" ].ToString ( ) );
                   }
               }
               else
               {
                   return DateTime.Now.Day; 
               }
           }
            set
            {
                ViewState [ "Day" ] = value;
            }
        }

        //传进来的讲师
        private string RequestTea
        {
            get
            {
                if (ViewState["Retea"] != null)
                {
                    return ViewState["Retea"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["Retea"] = value;
            }
        }
        //选择的讲师
        public string SelectTea
        {
            get 
            {
                if (ViewState["Setea"] != null)
                {
                    return ViewState["Setea"].ToString();
                }
                else
                    return "";
            
            }
            set 
            {
                ViewState["Setea"] = value;
            }
        }

        //选择的讲师
        private string TeaName
        {
            get
            {
                if (ViewState["TeaName"] != null)
                {
                    return ViewState["TeaName"].ToString();
                }
                else
                    return "";

            }
            set
            {
                ViewState["TeaName"] = value;
            }
        }

        public string RebackDate
        {
            get { return DateTime.Now.ToShortDateString(); }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // 权限 
            if (this.UserId == null)
            {
                Response.Redirect("/Error.aspx?message=1&functionId=" + FunctionID);
                return;
            }
            if (!CheckFunctionRight())
            {
                Response.Redirect("/Error.aspx?message=2&functionId=" + FunctionID);
                return;
            }
            if (!this.IsPostBack)
            {
                if (Request.QueryString["TYPE"] != null)
                {
                    SelectTea = RequestTea = this.User.UserID.ToString();
                }
                else
                {
                    SelectTea = RequestTea = Request.QueryString["TEAID"];
                    if (this.User.LoginName == "admin")
                    {
                        hdfadduser.Value = "TRUE";
                    }
                    else
                    {
                        hdfadduser.Value = this.User.UName;
                    }
                }
                bl_DataBind("");
            }

        }
        /// <summary>
        /// 绑定推广讲师
        /// </summary>
        private void bl_DataBind(string teacherName)
        {
            List<ZX.CRM.Library.V_GetUserByPositions> vu = GetTeacher(teacherName);
            if (vu != null)
            {
                blInnerTeacher.DataSource = vu;
                blInnerTeacher.DataTextField = "UName";
                blInnerTeacher.DataValueField = "UserID";
                blInnerTeacher.DataBind();
                if (SelectTea == "")
                {
                    SelectTea = vu[0].UserID.ToString();
                    TeaName = vu[0].UName;

                }
                else
                {
                    try
                    {
                        TeaName = vu.Where(p => p.UserID.ToString() == SelectTea).First().UName;
                    }
                    catch (Exception)
                    {
                        SelectTea = RequestTea = "";
                    }
                }
            }
            dl_DataBind();
        }
        private void dl_DataBind ()
        {
            string teachid = SelectTea;
            
            DateTime dt = new DateTime ( year, month, 1 );
            int w =  (int)dt.DayOfWeek;

            int daysInMonth = calender.GetDaysInMonth ( year, month );
            ArrayList date = new ArrayList ();          //定义日历展示用的数组
            for ( int i = 0;i < w;i++ )
            {
                date.Add (0);
            }
            for ( int i = 0;i < daysInMonth;i++ )
                date.Add( i + 1 );

            dl_Calendar.DataSource = GetDtByPara(date, GetV_CrmTeachHodometerList(teachid));
            dl_Calendar.DataBind ( );
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Review", "ReviewForm('"+sb+"')", true);
        }
        protected IList<ZX.CRM.Library.V_CrmTeachHodometer> GetV_CrmTeachHodometerList(string tchid)
        {
            ZX.CRM.Library.V_CrmTeachHodometer vcth = new ZX.CRM.Library.V_CrmTeachHodometer();
            BaseBussnies bvcth = new BaseBussnies(vcth);
            IList<ZX.CRM.Library.V_CrmTeachHodometer> vcthl = bvcth.GetEntitys<ZX.CRM.Library.V_CrmTeachHodometer>(" teachid='" + tchid + "' and  YEAR(hmdate) = '" + year + "' AND MONTH(hmdate) = '" + month + "'");
            return vcthl;
        }

        //整合数据源
        protected DataTable GetDtByPara(ArrayList date,IList<ZX.CRM.Library.V_CrmTeachHodometer> vcthl)
        {
            DataTable dt = new DataTable();
            #region 创建新列、定义汇总数
            DataColumn dc1 = new DataColumn("DTime", Type.GetType("System.String"));//日期
            DataColumn dc2 = new DataColumn("SW", Type.GetType("System.String"));//上午
            DataColumn dc3 = new DataColumn("SWid", Type.GetType("System.String"));//行程ID
            DataColumn dc4 = new DataColumn("SWname", Type.GetType("System.String"));//上午客户信息
            DataColumn dc5 = new DataColumn("XW", Type.GetType("System.String"));
            DataColumn dc6 = new DataColumn("XWid", Type.GetType("System.String"));
            DataColumn dc7 = new DataColumn("XWname", Type.GetType("System.String"));
            DataColumn dc8 = new DataColumn("WS", Type.GetType("System.String"));
            DataColumn dc9 = new DataColumn("WSid", Type.GetType("System.String"));
            DataColumn dc10 = new DataColumn("WSname", Type.GetType("System.String"));
            DataColumn dc11 = new DataColumn("Nums", Type.GetType("System.String"));
            DataColumn dc12 = new DataColumn("SWCusid", Type.GetType("System.String"));
            DataColumn dc13= new DataColumn("XWCusid", Type.GetType("System.String"));
            DataColumn dc14 = new DataColumn("WSCusid", Type.GetType("System.String"));
            dt.Columns.Add(dc1); 
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3); 
            dt.Columns.Add(dc4); 
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6); 
            dt.Columns.Add(dc8);
            dt.Columns.Add(dc7); 
            dt.Columns.Add(dc9);
            dt.Columns.Add(dc10); dt.Columns.Add(dc11); dt.Columns.Add(dc12); dt.Columns.Add(dc13); dt.Columns.Add(dc14);
            #endregion
            int nul = 1;
            foreach(int item in date)
            {
                DataRow dr = dt.NewRow();
                IList<ZX.CRM.Library.V_CrmTeachHodometer> vil=null;
                if (vcthl!=null)
                    vil = vcthl.Where(V => V.HmDate.Day == Convert.ToInt32(item)).ToList<ZX.CRM.Library.V_CrmTeachHodometer>();
                dt.Rows.Add(AddRow(nul,dr, item, vil));//.Where(p=>p.Sex ==True)
                nul++;
            }
            return dt;
        }

        //行赋值
        protected DataRow AddRow(int nul,DataRow dr,int dtime, IList<ZX.CRM.Library.V_CrmTeachHodometer> vcthl)
        {
            dr["Nums"] = nul;
            if (dtime == 0)
            {
                dr["DTime"] = nul.ToString() + nul.ToString() + "0";
                dr["SW"] = "";
                dr["SWid"] = "";
                dr["SWname"] = "";
                dr["XW"] = "";
                dr["XWid"] = "";
                dr["XWname"] = "";
                dr["WS"] = "";
                dr["WSid"] = "";
                dr["WSname"] = "";
                dr["SWCusid"] = "";
                dr["XWCusid"] = "";
                dr["WSCusid"] = "";
            }
            else
            {
                
                IList<ZX.CRM.Library.V_CrmTeachHodometer> va=null;
                IList<ZX.CRM.Library.V_CrmTeachHodometer> vp=null;
                IList<ZX.CRM.Library.V_CrmTeachHodometer> vn=null;
                if (vcthl != null && vcthl.Count!=0)
                {
                    va = vcthl.Where(V => V.HmType == "上午").ToList<ZX.CRM.Library.V_CrmTeachHodometer>();
                    vn = vcthl.Where(V => V.HmType == "晚上").ToList<ZX.CRM.Library.V_CrmTeachHodometer>();
                    vp = vcthl.Where(V => V.HmType == "下午").ToList<ZX.CRM.Library.V_CrmTeachHodometer>();
                }
                
                dr["DTime"] = dtime;
                dr["SW"] = "上午";
                if (va != null && va.Count!=0)
                {
                    dr["SWid"] = va[0].ThodometerId;
                    dr["SWname"] = va[0].CustomerName + "[" + va[0].Decisionmaker + "](" + va[0].DecisionPosition + "){" + va[0].EXP1 + "}{" + va[0].EXP2+"}--"+va[0].addusername;
                    dr["SWCusid"] = va[0].CusID;
                    if (!sb.ToString().Contains(va[0].addusername))
                    {
                        sb+=va[0].addusername + ";";
                    }
                }
                else
                { 
                    dr["SWid"] = "";
                    dr["SWname"] = "";
                    dr["SWCusid"] = "";
                }
                dr["XW"] = "下午";
                if (vp != null && vp.Count != 0)
                {
                    dr["XWid"] = vp[0].ThodometerId;
                    dr["XWname"] = vp[0].CustomerName + "[" + vp[0].Decisionmaker + "](" + vp[0].DecisionPosition + "){" + vp[0].EXP1 + "}{" + vp[0].EXP2 + "}--" + vp[0].addusername;
                    dr["XWCusid"] = vp[0].CusID;
                    if (!sb.ToString().Contains(vp[0].addusername))
                    {
                        sb+=vp[0].addusername + ";";
                    }
                }
                else
                {
                    dr["XWid"] = "";
                    dr["XWname"] = "";
                    dr["XWCusid"] = "";
                }
                dr["WS"] = "晚上";
                if (vn != null && vn.Count != 0)
                {
                    dr["WSid"] = vn[0].ThodometerId;
                    dr["WSname"] = vn[0].CustomerName + "[" + vn[0].Decisionmaker + "](" + vn[0].DecisionPosition + "){" + vn[0].EXP1 + "}{" + vn[0].EXP2 + "}--" + vn[0].addusername;
                    dr["WSCusid"] = vn[0].CusID;
                    if (!sb.ToString().Contains(vn[0].addusername))
                    {
                        sb+=vn[0].addusername + ";";
                    }
                }
                else
                {
                    dr["WSid"] = "";
                    dr["WSname"] = "";
                    dr["WSCusid"] = "";
                }
            }
            return dr;
        }
        protected void dl_Command ( object sender, CommandEventArgs e )
        {
            switch ( e.CommandName )
            {
                case "Pre":
                    if ( month == 1 )
                    {
                        year = year - 1;
                        month = calender.GetMonthsInYear(year);
                    }
                    else
                    {
                        month = month - 1;
                    }
                    dl_DataBind ( );
                    break;

                case "PreY":
                    year = year - 1;
                    dl_DataBind();
                    break;

                case "Next":
                    if ( month == calender.GetMonthsInYear(year))
                    {
                        year = year + 1;
                        month = 1;
                    }
                    else
                    {
                        month = month + 1;
                    }
                    dl_DataBind ( );
                    break;
                case "NextY":
                    year = year + 1;
                    dl_DataBind();
                    break;
            }
        }
        protected void blInnerTeacher_OnClick(object sender, BulletedListEventArgs e)
        {
            ListItem li = blInnerTeacher.Items[e.Index];
            SelectTea = li.Value;
            TeaName = li.Text;
            dl_DataBind();
        }
        protected void btnSerch_OnClick(object sender, EventArgs e)
        {
            bl_DataBind(teacherName.Value);
        }
        protected void dl_Calendar_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                Label lab_Time = (Label)e.Item.FindControl("lab_Time");
                lab_Time.Text = year + "-" + month;

                Label labt = (Label)e.Item.FindControl("Labteacher");
                labt.Text = TeaName;
            }
        }

        //获取讲师
        protected List<ZX.CRM.Library.V_GetUserByPositions> GetTeacher(string teacherName)
        {
            ZX.CRM.Library.V_GetUserByPositions vgubp = new ZX.CRM.Library.V_GetUserByPositions();
            BaseBussnies bgubp = new BaseBussnies(vgubp);

            bgubp.Order = "LoginName";
            bgubp.Desc = "No";
            string sContdition = getRoleCondition();
            sContdition = sContdition.Substring(0, 1);
            if (sContdition == "0")
            {
                sContdition = " (PositionName like '%推广讲师%') and UserID='"+this.UserId+"' and isexpire=0 ";
            }
            else {
                sContdition = " (PositionName like '%推广讲师%') and isexpire=0 ";
            }
            if (teacherName!="")
            {
                sContdition = sContdition + " and UName like '%"+teacherName.Replace("'","")+"%'";
            }
            IList<ZX.CRM.Library.V_GetUserByPositions> Ivl = bgubp.GetEntitys<ZX.CRM.Library.V_GetUserByPositions>(sContdition);
            if (Ivl != null)
            {
                return Ivl.ToList<ZX.CRM.Library.V_GetUserByPositions>();
            }
            else
            {
                List<ZX.CRM.Library.V_GetUserByPositions> vgubpl = null;
                return vgubpl;
            }
        }
        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.UserId, this.FunctionID);
            string strCondition = "";

            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        strCondition = "0" + this.User.UName;
                        break;
                    ///可以看本部门的
                    case "1":
                        strCondition = "1" + this.User.UName;
                        return strCondition;
                        break;
                    //// 全部数据
                    //case "2":
                    //    break;
                    ////自定义部门条件
                    //case "3":
                    //    // 如果自定义条件
                    //    if (strCondition.ToString() != "")
                    //    {
                    //        strCondition.Append(" OR ");
                    //    }
                    //    strCondition.Append(string.Format(" UserID in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                    //    break;
                    //// 自定义条件数据
                    //case "4":
                    //    if (strCondition.ToString() != "")
                    //    {
                    //        strCondition.Append(" OR ");
                    //    }
                    //    if (entity.Condition != string.Empty)
                    //    {
                    //        strCondition.Append(" " + entity.Condition + " ");
                    //    }
                    //    break;
                    default:
                        strCondition = "1" + this.User.UName;
                        return strCondition;
                        break;
                }
            }

            return strCondition;
        }
    }
}